//
//  XLGDownloadDBOperation.m
//  etionCBLogic
//
//  Created by wjxfhxy on 15-2-27.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XLGDownloadDBOperation.h"

NSString *const DownloadTable = @"download";

@implementation XLGDownloadDBOperation
{
	XMSSQLiteHelper* _sqlHelper;
}

- (id)initWithTablePath:(NSString*)tablePath
{
    self = [super init];
    
	_sqlHelper = [XMSSQLiteHelper new];
    
    [_sqlHelper openTable:tablePath flags:SQLITE_OPEN_READWRITE| SQLITE_OPEN_FULLMUTEX];
    
	return self;
}

-(void)dealloc
{
	if(_sqlHelper != nil)
		[_sqlHelper closeTable];
	[_sqlHelper release_mm];
	superdealloc_mm;
}

- (NSInteger)addDownloadIndex:(XLGDownloadIndex *)mi
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    NSArray *array = @[[CSQLKv SQLkvWithKey:@"extendid" value:mi.extendID type:ESQLKvVarTypeString],
                       [CSQLKv SQLkvWithKey:@"sourceType" value:@(mi.sourceType) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"totalbyte" value:@(mi.totalByte) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"downloadbyte" value:mi.downloadByte type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"submittime" value:mi.submitTime type:ESQLKvVarTypeDateTime],
                       [CSQLKv SQLkvWithKey:@"downloadtime" value:mi.downloadTime type:ESQLKvVarTypeDateTime],
                       [CSQLKv SQLkvWithKey:@"downloadstatus" value:@(mi.downloadStatus) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"serialno" value:@(mi.serialNo) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"title" value:mi.title type:ESQLKvVarTypeString],
                       [CSQLKv SQLkvWithKey:@"URL" value:mi.URL type:ESQLKvVarTypeString],
                       [CSQLKv SQLkvWithKey:@"targettype" value:@(mi.targetType) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"channeltype" value:@(mi.channelType) type:ESQLKvVarTypeInt],
                       [CSQLKv SQLkvWithKey:@"storename" value:mi.storeName type:ESQLKvVarTypeString]];
    
    NSInteger nResult = [sqlHelper runInsert:DownloadTable kv:array];
    
    return nResult;
}

- (void)getDownloadIndexByCondition:(NSString*)condition completion:(void(^)(NSInteger nResult, NSArray *items))completion
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    
    NSString *sql = [NSString stringWithFormat:@"select extendid,sourceType,totalbyte,downloadbyte,submittime,downloadtime,downloadstatus,serialno,title,URL,targettype,channeltype,storename from %@",DownloadTable];
    
    if(condition.length > 0)
        sql = [NSString stringWithFormat:@"%@ where %@",sql,condition];
    
    NSMutableArray *array = [[NSMutableArray new] autorelease_mm];
    
    NSInteger nResult = [sqlHelper selectTable:[sql UTF8String] gettingTable:^(BOOL *bStop)
    {
        XLGDownloadIndex *index = [[XLGDownloadIndex new]autorelease_mm];
        [array addObject:index];
        
        index.extendID = [sqlHelper getFieldNSString:0];
        index.sourceType = [sqlHelper getFieldInt:1];
        index.totalByte = [sqlHelper getFieldInt:2];
        index.downloadByte = [sqlHelper getFieldInt:3];
        index.submitTime = [sqlHelper getFieldNSDate:4];
        index.downloadTime = [sqlHelper getFieldNSDate:5];
        index.downloadStatus = [sqlHelper getFieldInt:6];
        index.serialNo = [sqlHelper getFieldInt:7];
        index.title = [sqlHelper getFieldNSString:8];
        index.URL = [sqlHelper getFieldNSString:9];
        index.targetType = [sqlHelper getFieldInt:10];
        index.channelType = [sqlHelper getFieldInt:11];
        index.storeName = [sqlHelper getFieldNSString:12];
    }];
    
    completion(nResult,array);
}

- (void)getDownloadIndexCompletion:(void (^)(NSInteger nResult, NSArray *index))completion
{
    [self getDownloadIndexByCondition:[NSString stringWithFormat:@"targettype = %@ order by serialno asc",@(XLGDownloadTargetTypeDownload)] completion:completion];
}

- (void)getFinishedIndexCompletion:(void(^)(NSInteger nResult, NSArray *index))completion
{
    [self getDownloadIndexByCondition:[NSString stringWithFormat:@"targettype = %@ order by downloadtime desc limit 100",@(XLGDownloadTargetTypeFinished)] completion:completion];
}

- (void)getIndex:(XLGDownloadTargetType)targetType withSourceType:(NSUInteger)sourceType completion:(void (^)(NSInteger nResult, NSArray *index))completion
{
    [self getDownloadIndexByCondition:[NSString stringWithFormat:@"targettype = %@ and sourceType = %@ order by serialno asc",@(targetType),@(sourceType)] completion:completion];
}

- (void)getIndexWithExtendIDs:(NSArray*)extendIDs completion:(void (^)(NSInteger nResult, NSArray *index))completion
{
    NSString *s = [NSString megerStringWithTag:extendIDs value:^NSString *(id obj)
    {
        return [NSString stringWithFormat:@"extendID = '%@'",obj];
    } tag:@" or "];
    [self getDownloadIndexByCondition:s completion:completion];
}

- (void)getIndexWithURLs:(NSArray*)URLs completion:(void (^)(NSInteger nResult, NSArray *index))completion
{
    NSString *s = [NSString megerStringWithTag:URLs value:^NSString *(id obj)
    {
        return [NSString stringWithFormat:@"URL = '%@'",obj];
    } tag:@" or "];
    [self getDownloadIndexByCondition:s completion:completion];
}

- (NSInteger)deleteIndexWithCondition:(NSString*)condition
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    return [sqlHelper runDelete:DownloadTable condition:condition];
}

- (NSInteger)deleteIndexWithExtendID:(NSArray*)extendIDs
{
    NSString *s = [NSString megerStringWithTag:extendIDs value:^NSString *(id obj)
    {
        return [NSString stringWithFormat:@"extendid = '%@'",obj];
    } tag:@" or "];
    return [self deleteIndexWithCondition:s];
}

-(NSInteger)deleteIndexWithURLs:(NSArray*)URLs
{
    NSString *s = [NSString megerStringWithTag:URLs value:^NSString *(id obj)
    {
        return [NSString stringWithFormat:@"URL = '%@'",obj];
    } tag:@" or "];
    return [self deleteIndexWithCondition:s];
}

/*
- (NSInteger)modifyDownloadIndexSerialNo:(NSInteger(^)(NSInteger(^modify)(NSUInteger serialNo,NSString* extendID)))block
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    NSInteger nResult = [sqlHelper transExce:^NSInteger
    {
        NSInteger(^modify)(NSUInteger serialNo,NSString* externID)=^NSInteger(NSUInteger serialNo,NSString* extendID)
        {
            CSQLKv *condition = [CSQLKv SQLkvWithKey:@"extendid" value:extendID type:ESQLKvVarTypeString];
            CSQLKv *value = [CSQLKv SQLkvWithKey:@"serialno" value:@(serialNo) type:ESQLKvVarTypeInt];
            return [sqlHelper runUpdate:DownloadTable valueKv:@[value] conditionKv:@[condition]];
        };
        
        return block(modify);
    }];
    return nResult;
}
*/

- (NSInteger)modifyDownloadIndexStatus:(NSInteger(^)(NSInteger(^modify)(NSUInteger serialNo,NSString* extendID,XLGDownloadStatusType status)))block
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    NSInteger nResult = [sqlHelper transExce:^NSInteger
    {
        NSInteger(^modify)(NSUInteger serialNo,NSString* extendID,XLGDownloadStatusType status)=^NSInteger(NSUInteger serialNo,NSString* extendID,XLGDownloadStatusType status)
        {
            CSQLKv *condition = [CSQLKv SQLkvWithKey:@"extendid" value:extendID type:ESQLKvVarTypeString];
            CSQLKv *value1 = [CSQLKv SQLkvWithKey:@"serialno" value:@(serialNo) type:ESQLKvVarTypeInt];
            CSQLKv *value2 = [CSQLKv SQLkvWithKey:@"downloadstatus" value:@(status) type:ESQLKvVarTypeInt];
            return [sqlHelper runUpdate:DownloadTable valueKv:@[value1,value2] conditionKv:@[condition]];
        };
        return block(modify);
    }];
    return nResult;
}

- (NSInteger)modifyFinishDownloadIndex:(NSString*)extendID
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    
    CSQLKv *condition = [CSQLKv SQLkvWithKey:@"extendid" value:extendID type:ESQLKvVarTypeString];
    CSQLKv *value1 = [CSQLKv SQLkvWithKey:@"downloadtime" value:[NSDate date] type:ESQLKvVarTypeDateTime];
    CSQLKv *value2 = [CSQLKv SQLkvWithKey:@"serialno" value:@(9999) type:ESQLKvVarTypeInt];
    CSQLKv *value3 = [CSQLKv SQLkvWithKey:@"targettype" value:@(XLGDownloadTargetTypeFinished) type:ESQLKvVarTypeInt];
    CSQLKv *value4 = [CSQLKv SQLkvWithKey:@"downloadstatus" value:@(XLGDownloadStatusTypeFinished) type:ESQLKvVarTypeInt];
    
    return [sqlHelper runUpdate:DownloadTable valueKv:@[value1,value2,value3,value4] conditionKv:@[condition]];
}

- (NSInteger)updateDownloadItem:(NSString *)extendID fileTotalByte:(NSUInteger)totalByte downloadByte:(NSUInteger)downloadByte
{
    XMSSQLiteHelper *sqlHelper = [[[XMSSQLiteHelper alloc]initWithSQLiteHelper:_sqlHelper] autorelease_mm];
    
    if(totalByte > 0)
    {
        CSQLKv *condition = [CSQLKv SQLkvWithKey:@"extendid" value:extendID type:ESQLKvVarTypeString];
        CSQLKv *value1 = [CSQLKv SQLkvWithKey:@"totalbyte" value:@(totalByte) type:ESQLKvVarTypeInt];
        CSQLKv *value2 = [CSQLKv SQLkvWithKey:@"downloadbyte" value:@(downloadByte) type:ESQLKvVarTypeInt];
        
        return [sqlHelper runUpdate:DownloadTable valueKv:@[value1,value2] conditionKv:@[condition]];
    }
    else
    {
        CSQLKv *condition = [CSQLKv SQLkvWithKey:@"extendid" value:extendID type:ESQLKvVarTypeString];
        CSQLKv *value2 = [CSQLKv SQLkvWithKey:@"downloadbyte" value:@(downloadByte) type:ESQLKvVarTypeInt];
        
        return [sqlHelper runUpdate:DownloadTable valueKv:@[value2] conditionKv:@[condition]];
    }
    return NO;
}

@end
